﻿

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public class WebUtility
{
    public delegate void OnHttpResponse(HttpStatusCode code, string response);

    public static async Task<string> HttpGet(string url,Dictionary<string,object> param, /*OnHttpResponse onSuc, */Action<string> onFailed)
    {
        string paramStr = "";
        if (param != null)
        {
            foreach (var pair in param)
            {
                if (string.IsNullOrEmpty(paramStr))
                    paramStr = $"?{pair.Key}={pair.Value}";
                else
                    paramStr += $"&{pair.Key}={pair.Value}";
            }
        }
        url += paramStr;
        string res = await HttpRequest(url, "GET", "application/text", null,/* onSuc*/ onFailed);
        return res;
    }

    public static async Task<string> HttpPost(string url, object param, /*OnHttpResponse onSuc,*/ Action<string> onFailed)
    {
        var res = await HttpRequest(url, "POST", param != null ? "application/json" : "", param, /*onSuc, */onFailed);
        return res;
    }
    public static async Task<string> HttpRequest(string url,string method,string contentType,object param,/* OnHttpResponse onSuc,*/Action<string>onFailed)
    {
        GameDebug.Log($"{method} 请求：{url}");

        var request = WebRequest.Create(url) as HttpWebRequest;
        request.ProtocolVersion = HttpVersion.Version10;
        request.Timeout = 10000;
        request.Method = method;
        if (!string.IsNullOrEmpty(contentType))
        {
            request.ContentType = contentType;
        }
        if (param != null)
        {
            string requestBody = Newtonsoft.Json.JsonConvert.SerializeObject(param);
            //GameDebug.Log($"requestBody:{requestBody}");
            var postData = Encoding.UTF8.GetBytes(requestBody);
            request.ContentLength = postData.Length;

            using (var postStream = request.GetRequestStream())
            {
                postStream.Write(postData, 0, postData.Length);
            }
        }
        
        Stream stream = null;
        StreamReader streamReader = null;
        WebResponse webResponse = null;
        try
        {
            webResponse = request.GetResponse();
            stream = webResponse.GetResponseStream();

            if (stream != null)
            {
                streamReader = new StreamReader(stream, Encoding.UTF8);
                string res = streamReader.ReadToEnd();

                HttpWebResponse httpWebResponse = (HttpWebResponse)webResponse;

                return res;
               // onSuc?.Invoke(httpWebResponse.StatusCode,res);
            }
            else
            {
                onFailed?.Invoke("response stream null");
            }
        }
        catch (HttpRequestException e)
        {
            if (e.InnerException != null) 
                GameDebug.LogError("error: " + e.InnerException.Message);
           onFailed?.Invoke(e.Message);
        }
        catch (Exception e)
        {
            GameDebug.LogException(e);
            onFailed?.Invoke(e.Message);
        }
        finally
        {
            streamReader?.Close();
            stream?.Close();
            //webResponse.Close();
            //webResponse?.Dispose();
        }

        return null;
    }

}
